package org.fly.controller.wap.supplier;

import org.fly.bean.*;
import org.fly.bean.query.CustomerLevelQuery;
import org.fly.bean.query.CustomerQuery;
import org.fly.bean.query.PageQuery;
import org.fly.bean.query.SCLRQuery;
import org.fly.bean.warpper.SCLRWarpper;
import org.fly.controller.AbstractController;
import org.fly.service.CustomerLevelService;
import org.fly.service.CustomerService;
import org.fly.service.SCLRService;
import org.fly.utils.JsonUtils;
import org.fly.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by rongzhao.zhu on 2018/2/18.
 */
@Controller
@RequestMapping("/wap/supplier/customer/")
public class WapSCustomerController extends AbstractController {

    @Autowired
    SCLRService sclrService;
    @Autowired
    CustomerLevelService customerLevelService;
    @Autowired
    CustomerService customerService;


    @RequestMapping(value = "queryPage", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryPage(SCLRQuery query){

        List<SCLRWarpper> list = sclrService.listWarpper(query);
        long count = this.sclrService.count(query);
        Page page = new Page(query.getPage(),query.getSize());
        page.setData(list);
        page.setTotal(count);
        return JsonUtils.encode(createDataTip(page));
    }
    @RequestMapping(value = "queryForSCLREdit", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryForSCLREdit(String id){
        SCLR sclr =  sclrService.findById(id);
        Supplier supplier = (Supplier) UserContext.getUser();
        CustomerLevelQuery query = new CustomerLevelQuery();
        query.setSupplierId(supplier.getId());
        List<CustomerLevel>  customerLevels = customerLevelService.list(query);
        Map<String,Object> map = new HashMap<>();
        map.put("sclr",sclr);
        map.put("customerLevels",customerLevels);
        if(sclr != null ){
            Customer customer =  customerService.findById(sclr.getCustomerId());
            map.put("customer",customer);

        }
        return JsonUtils.encode(createDataTip(map));
    }
    @RequestMapping(value = "save", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String save(SCLR sclr, HttpServletRequest request){
        try {
            sclrService.save(sclr);
            return toJSONString(SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return toExceptionString(e);
        }
    }

}
